package com.xiangban.yanglaodajie_platform.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xiangban.yanglaodajie_platform.config.AliYunParameterConfig;
import com.xiangban.yanglaodajie_platform.entity.res.ApiResultCode;
import com.xiangban.yanglaodajie_platform.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

@Component
public class ALiYunSms {

    @Autowired
    private AliYunParameterConfig aliYunParameterConfig;

    private static ALiYunSms aLiYunSms;

    @PostConstruct
    public void init(){
        aLiYunSms = this;
    }
    public static void sendSms(String smsTemplate, String mobile, Map<String,Object> templateParam){
        DefaultProfile profile = DefaultProfile.getProfile(aLiYunSms.aliYunParameterConfig.getRegionId(), aLiYunSms.aliYunParameterConfig.getAccessKeyId(), aLiYunSms.aliYunParameterConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        if (!templateParam.isEmpty()) {
            String templateParamString = JSONObject.toJSONString(templateParam);
            request.putQueryParameter("TemplateParam", templateParamString);
        }
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(aLiYunSms.aliYunParameterConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", aLiYunSms.aliYunParameterConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", aLiYunSms.aliYunParameterConfig.getSignName());
        request.putQueryParameter("TemplateCode", smsTemplate);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            throw new BizException(ApiResultCode.VERIFICATION_CODE);
        }
    }
}
